package com.iuie.ns.frame.json.advice;

import java.util.TimeZone;

import javax.annotation.Resource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.iuie.ns.frame.json.annotations.MyJsonFilter;
import com.iuie.ns.frame.json.annotations.MyJsonFilters;

public class MyJsonFilterAdvice {
	
	@Resource(name="jacksonMessageConverter")
	private MappingJackson2HttpMessageConverter jacksonMessageConverter;

	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		MethodSignature msig = (MethodSignature) pjp.getSignature();
		MyJsonFilter annotation = msig.getMethod().getAnnotation(MyJsonFilter.class);
		MyJsonFilters annotations = msig.getMethod().getAnnotation(MyJsonFilters.class);
		
		ObjectMapper mapper = getObjectMapper();
		jacksonMessageConverter.setObjectMapper(mapper);
		
		// 清空mixIns
		mapper.setMixIns(null);
		
		if (annotation == null && annotations == null) {
			return pjp.proceed();
		}

		if (annotation != null) {
			Class<?> mixin = annotation.mixin();
			Class<?> target = annotation.target();

			if (target != null) {
				mapper.addMixIn(target, mixin);
			} else {
				mapper.addMixIn(msig.getMethod().getReturnType(), mixin);
			}
		}

		if (annotations != null) {
			MyJsonFilter[] filters = annotations.value();
			for (MyJsonFilter filter : filters) {
				Class<?> mixin = filter.mixin();
				Class<?> target = filter.target();

				if (target != null) {
					mapper.addMixIn(target, mixin);
				} else {
					mapper.addMixIn(msig.getMethod().getReturnType(), mixin);
				}
			}

		}
		return pjp.proceed();
	}
	
	private ObjectMapper getObjectMapper() {
		ObjectMapper mapper = new ObjectMapper();
		TimeZone tz = TimeZone.getTimeZone("GMT+08");
		mapper.setTimeZone(tz);
		return mapper;
	}
}
